package com.yc.qunxing.web;

import com.yc.qunxing.result.Result;
import com.yc.qunxing.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;


/**
 * 通用接口
 */
@RestController
@RequestMapping("/drivers/common")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file);
        try {
            // 压缩图片
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Thumbnails.of(file.getInputStream())
                    .size(200, 200)
                    .outputQuality(0.8)
                    .toOutputStream(outputStream);

            // 获取压缩后的字节数组
            byte[] compressedBytes = outputStream.toByteArray();
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            String name = UUID.randomUUID().toString() + substring;
            //文件请求路径
            String upload = aliOssUtil.upload(compressedBytes, name);
            return Result.success(upload);
        } catch (IOException e) {
            log.error("文件上传失败: {}",e);
        }
        return Result.error("文件上传失败");
    }
}
